//
//  WQCShareViewController.m
//  renxinghuan
//
//  Created by 王晓民 on 2018/3/21.
//  Copyright © 2018年 吴清翠. All rights reserved.
//

#import "WQCShareViewController.h"
#import "configuration.h"
#import "WXApi.h"
@interface WQCShareViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,WXApiDelegate,WXDelegate>
{
    AppDelegate *appdelegate;

}
@property(nonatomic,strong)UICollectionView * mainCollectionView;
@property(nonatomic,strong) UIImageView *wechatImageView;
@property(nonatomic,strong)NSMutableArray *imgUrlArr;
@property(nonatomic,strong)NSMutableArray *moidArr;
@property(nonatomic,strong)UIImageView *imgView;
@property(nonatomic,strong)NSString *urlStr;
@property (nonatomic,strong)NSString *imageData;
@end

@implementation WQCShareViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationController.navigationBarHidden =NO;

    self.view.backgroundColor = WYCGlobalBg;
    
    self.imgUrlArr = [[NSMutableArray alloc]init];
    self.moidArr = [[NSMutableArray alloc]init];
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 5);
    layout.footerReferenceSize = CGSizeMake(self.view.frame.size.width, 5);
    
    //该方法也可以设置itemSize
    layout.itemSize =CGSizeMake(ScreenWidth/2-10, 230);
    
    _mainCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(10, NavHeight+10, ScreenWidth-10, ScreenHeight) collectionViewLayout:layout];
    [self.view addSubview:_mainCollectionView];
    _mainCollectionView.backgroundColor = WYCGlobalBg;
    //3.注册collectionViewCell
    //注意，此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
    [_mainCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellId"];
    
    //注册headerView  此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致  均为reusableView
    [_mainCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView"];
    
    //4.设置代理
    _mainCollectionView.delegate = self;
    _mainCollectionView.dataSource = self;
    [self setupNav];
    
    [self loadgetShareTemplate];
}
-(void)loadgetShareTemplate
{
    [HttpTool POST:getShareTemplate params:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSLog(@"moban%@",responseObject);
        if ([[responseObject objectForKey:@"code"] intValue] == 0) {
            
            NSDictionary  *result=[responseObject objectForKey:@"result"];
            NSArray  *arr=result[@"list"];
            _urlStr = result[@"url"];
            for (NSDictionary *dic in arr) {
                
                NSString  *moid = dic[@"id"];
                [self.moidArr addObject:moid];
                NSString  *imgUrl = dic[@"imgUrl"];
                [self.imgUrlArr addObject:imgUrl];

            }
            [_mainCollectionView reloadData];
        }
       

    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}

//设置分区数（必须实现）
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

//设置每个分区的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _imgUrlArr.count;
}

//设置返回每个item的属性必须实现）
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
  
    UICollectionViewCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"cellId" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    
    UIImageView  *bankBg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth/2, 220)];
    bankBg.userInteractionEnabled = YES;
   [bankBg sd_setImageWithURL:[NSURL URLWithString:[_imgUrlArr objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:@"bg"]];
   bankBg.contentMode =UIViewContentModeScaleAspectFit;
    [cell.contentView addSubview:bankBg];
    
    UIImageView *weima = [MyUIClass makeUIImageViewWithFrame:CGRectMake(75, 135, 40, 40) andImage:@""];
    weima.image=_wechatImageView.image;
    [bankBg addSubview:weima];
    
    return cell;
}



-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *templateId=[self.moidArr objectAtIndex:indexPath.row];
    NSLog(@"xiansi%@",templateId);
    [self loadshareImg:templateId];

}
-(void)loadshareImg:(NSString *)templateId
{
    [SVProgressHUD showWithStatus:@"上传中"];
    NSMutableDictionary * params = [NSMutableDictionary dictionary];

    params[@"templateId"] = templateId;

    [HttpTool POST:createTemplate params:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSLog(@"%@",responseObject);
        if ([[responseObject objectForKey:@"code"] intValue] == 0)
        {
            [SVProgressHUD dismiss];
            self.imageData = responseObject[@"result"];
            [self creatshareView];
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showImage:nil status:Failed];
    }];
}

-(void)creatshareView
{
    
    UIView *bgview = [MyUIClass makeUIViewWithFram:CGRectMake(0, 0, ScreenWidth, ScreenHeight) andBackColor:nil];
    bgview.backgroundColor=[UIColor  colorWithRed:40/255.0 green:42/255.0 blue:54/255.0 alpha:0.5];
    bgview.userInteractionEnabled=YES;
    [self.view addSubview:bgview];
    
    UIView *shareView = [MyUIClass makeUIViewWithFram:CGRectMake(0, ScreenHeight-100, ScreenWidth,100) andBackColor:[UIColor whiteColor]];
    [bgview addSubview:shareView];
    
    NSArray  *imgArr = @[@"weixin",@"qqimg",@"surl"];
    NSArray  *titleArr = @[@"微信",@"朋友圈",@"链接"];

    for (int i = 0; i<imgArr.count; i++)
    {
        
        UIButton  *btnank = [UIButton buttonWithType:UIButtonTypeCustom];
        btnank.frame = CGRectMake(ScreenWidth/3*i, 0, ScreenWidth/3, 100);
        btnank.tag = 900+i;
        [ btnank addTarget:self action:@selector(pressShare:) forControlEvents:UIControlEventTouchUpInside];
        
        [shareView addSubview:btnank];
        
        //通知imageView
        UIImageView *noticeimageView = [[UIImageView alloc] init];
        noticeimageView.frame = CGRectMake((ScreenWidth/3-44)/2, 10, 44, 44 );
        noticeimageView.image = [UIImage imageNamed:[imgArr objectAtIndex:i]];
        [btnank addSubview:noticeimageView];
        UILabel  *banLb = [[UILabel alloc]init];
        banLb.frame = CGRectMake(0, 60, ScreenWidth/3, 20);
        banLb.textAlignment  = NSTextAlignmentCenter;
        banLb.textColor = [UIColor blackColor];
        banLb.text = [titleArr objectAtIndex:i];
        banLb.font = [UIFont systemFontOfSize:13];
        [btnank addSubview:banLb];
    }
    
}

-(void)pressShare:(UIButton *)btn
{
    if(btn.tag == 900)
    {
        NSLog(@"微信好友");
        WXMediaMessage *message = [WXMediaMessage message];
        [message setThumbImage:[UIImage imageNamed:@"bank_01"]];
        
        WXImageObject *imageObject = [WXImageObject object];
        NSData *data =  [[NSData alloc]initWithBase64EncodedString:self.imageData options:(NSDataBase64DecodingIgnoreUnknownCharacters)];
        UIImage *image = [UIImage imageWithData:data];
        imageObject.imageData =UIImageJPEGRepresentation(image, 0.1);
        message.mediaObject = imageObject;
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
        req.bText = NO;
        req.message = message;
        req.scene = WXSceneSession;
        [WXApi sendReq:req];
    }
    else if (btn.tag == 901)
    {
        NSLog(@"朋友圈");

        WXMediaMessage *message = [WXMediaMessage message];
        [message setThumbImage:[UIImage imageNamed:@"bank_01"]];
        
        WXImageObject *imageObject = [WXImageObject object];
        NSData *data =  [[NSData alloc]initWithBase64EncodedString:self.imageData options:(NSDataBase64DecodingIgnoreUnknownCharacters)];
        UIImage *image = [UIImage imageWithData:data];
        imageObject.imageData =UIImageJPEGRepresentation(image, 0.1);
        message.mediaObject = imageObject;
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
        req.bText = NO;
        req.message = message;
        req.scene = WXSceneTimeline;
        [WXApi sendReq:req];
     }
    else if (btn.tag ==902)
    {
        NSLog(@"链接");
        UIPasteboard *pb = [UIPasteboard generalPasteboard];
        pb.string = self.urlStr;
        [SVProgressHUD showImage:nil status:@"复制成功，可以发给朋友们了"];
    }
    
}

- (void)setupNav {
    
    [self.navigationController.navigationBar setBarTintColor:wycMain];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationItem.title = @"我要分享";

}


#pragma mark 监听微信分享是否成功 delegate
-(void)shareSuccessByCode:(int)code{
    NSLog(@"成功");
//    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"分享成功" message:[NSString stringWithFormat:@"reason : %d",code] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", ];
//    [alert show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/**
// * 根据CIImage生成指定大小的UIImage
// *
// * @param image CIImage
// * @param size 图片宽度
// */
//- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
//{
//    CGRect extent = CGRectIntegral(image.extent);
//    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
//    // 1.创建bitmap;
//    size_t width = CGRectGetWidth(extent) * scale;
//    size_t height = CGRectGetHeight(extent) * scale;
//    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
//    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
//    CIContext *context = [CIContext contextWithOptions:nil];
//    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
//    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
//    CGContextScaleCTM(bitmapRef, scale, scale);
//    CGContextDrawImage(bitmapRef, extent, bitmapImage);
//    // 2.保存bitmap到图片
//    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
//    CGContextRelease(bitmapRef);
//    CGImageRelease(bitmapImage);
//    return [UIImage imageWithCGImage:scaledImage];
//}


/**
 *  设置返回按钮标题
 */
- (void)setBackBarButtonItemWithTitle:(NSString *)title
{
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setBackgroundColor:[UIColor clearColor]];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"NavBackSorrow"] forState:UIControlStateNormal];
    [btn setContentMode:UIViewContentModeScaleAspectFill];
    [btn setImageEdgeInsets:UIEdgeInsetsMake(0, -7, 0, 50)];
    [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 10)];
    [btn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = barButtonItem;
}

/**
 *  返回按钮点击事件
 */
- (void)backAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
